package com.pow.service.impl;

import com.pow.entity.Role;
import com.pow.entity.User;
import com.pow.repository.RoleRepository;
import com.pow.repository.UserRepository;
import com.pow.service.UserService;
import com.pow.util.FenyeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.data.domain.Pageable;
import javax.persistence.criteria.*;
import javax.transaction.Transactional;

import java.util.List;

/**
 * @author 赵祺
 * @date 2020/4/13 16:46
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Override
    public FenyeUtil<User> findAllPageByUser(User user, Pageable pageable,Integer page) {
        FenyeUtil<User> fenyeUtil=new FenyeUtil<>();
        Pageable pageable1= PageRequest.of(page-1,10);
        Page<User> userPageList=userRepository.findAll(get(user),  pageable1);
        List<User> content = userPageList.getContent();
        long totalElements = userPageList.getTotalElements();
        fenyeUtil.setCount((int) totalElements);
        fenyeUtil.setData(content);
        fenyeUtil.setCode(0);
        fenyeUtil.setMsg("");
        return fenyeUtil;
    }

    private Specification<User> get(User user) {
        return  new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = predicate.getExpressions();
                if(!StringUtils.isEmpty(user.getLoginName())){
                    expressions.add(criteriaBuilder.like(root.get("loginName"),"%"+user.getLoginName()+"%"));
                }

                return predicate;
            }
        };
    }

    @Override
    public String AddAndUpdateUser(User user) {
        try {
            userRepository.saveAndFlush(user);
            return  "操作成功";
        }catch (Exception e){
            e.printStackTrace();
            return  "操作失败";
        }
    }

    @Override
    public String deleteUser(String id) {
        try {
            userRepository.deleteById(id);
            return  "操作成功";
        }catch (Exception e){
            e.printStackTrace();
            return  "操作失败";
        }
    }

	@Override
	public FenyeUtil<Role> getNotRoleById(String id) {
		FenyeUtil<Role> f=new FenyeUtil<Role>();
		f.setData(roleRepository.getNotRoleById(id));//把查询的角色数据存入data
		
		f.setCount(roleRepository.getNotRoleById(id).size());//把数据条数存入count
		return f;
	}

	@Override
	
	public Integer commitUser_Role(String uid, String rid) {
		try {
			String[] rids=rid.split(",");//把rid分割成数组
			List<String> urids=userRepository.getRidsByUid(uid);//获得当前用户的角色信息
			for(int i=0;i<rids.length;i++) {
				Integer c=userRepository.getUser_Role(uid, rids[i]);
				System.out.println("c:"+c);
				if(c==0) {//判断该用户是否存在此角色 >0 存在  =0不存在					
					System.out.println("添加了");
					userRepository.addUser_Role(uid, rids[i]);
				}
				//判断需要保存的值是否与之前存在的有重复 重复就删掉 剩下的删除
				for(int a=0;a<urids.size();a++) {
					if(rids[i].equals(urids.get(a))) {
						urids.remove(a);						
					}else {
						continue;
					}
				}
			
			}
			for(int i=0;i<rids.length;i++) {
				//判断需要保存的值是否与之前存在的有重复 重复就删掉 剩下的删除
				for(int a=0;a<urids.size();a++) {
					if(rids[i].equals(urids.get(a))) {
						urids.remove(a);						
					}else {
						continue;
					}
				}
			
			}
			
			for(int i=0;i<urids.size();i++) {
				userRepository.deleteUser_Role(uid, urids.get(i));
			}
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		
		
		
	}

	@Override
	public Integer getUser_Role(String uid, String rid) {
		
		return userRepository.getUser_Role(uid, rid);
	}

	@Override
	
	public Integer addUser_Role(String uid, String rid) {
		try {
			userRepository.addUser_Role(uid, rid);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		
	}

	@Override
	
	public Integer deleteUser_Role(String uid, String rid) {
		try {
			userRepository.deleteUser_Role(uid, rid);
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	
	public List<String> getRidsByUid(String uid) {
		return userRepository.getRidsByUid(uid);
	}
}
